import logging
import traceback
import peres.parser
import genny.warkup_generator

from waveapi.document import Range

class Mark(object):
    
    def _replace_text(self, doc, old_text, new_text, position):
        if old_text == new_text: 
            return
    
        logging.debug("inserting: %s at %d" % (new_text, position))
        doc.InsertText(position, new_text)
        
        start = len(new_text)+position
        end = len(new_text)+position+len(old_text)
        logging.debug("deleting: from %d at %d" % (start, end))
        doc.DeleteRange(Range(start,end))
        
    
    def _describe_anns(self, anns):
        return "\n".join(["[ann: (%s,%s) range:%d,%d]" % (a.name, a.value, a.range.start, a.range.end) for a in anns])
    
    def OnRobotAdded(self, properties, context):
        """Invoked when the robot has been added."""
        root_wavelet = context.GetRootWavelet()
        root_wavelet.CreateBlip().GetDocument().SetText("Hi everybody! my name is Mark. You can now write markup inside your wave message and if I know what it means, I'll replace it with a link or a gadget")

    def OnBlipSubmitted(self, properties, context):
        """Invoked when a blip is created."""
        blip = context.GetBlipById(properties['blipId'])
        doc = blip.GetDocument()
         
        logging.debug("\n\n\nFound existing annotations:\n\n" + self._describe_anns(blip.GetAnnotations()) + "\n\n\nEOF")
                                
        text = doc.GetText()
        changes = genny.warkup_generator.render_warkup(text)
        changes.reverse()
        
        logging.debug("\n\n\n\nReturned Changes:\n" + "\n".join([str(x) for x in changes]) + "\n\n\nEOF")
        
        for change in changes:
            self._replace_text(doc, change.get_original_text(), change.get_new_text(), change.get_original_position())
        
        
        logging.debug("\n\n\nAnnotations after changes:\n\n" + self._describe_anns(blip.GetAnnotations()) + "\n\n\nEOF")
        